package screen;

import java.io.IOException;
import java.util.Enumeration;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

import files.Files;

import book.Book;

public class BooksBrowser implements CommandListener {

	private static final String LIBRARY_FOLDER = Files.BOOK_ROOT;

	private Command view = new Command("Choisir", Command.ITEM, 1);
	
	private List browser;

	public void commandAction(Command c, Displayable d) {
		if (c == view) {
			List curr = (List) d;
			String currFile = curr.getString(curr.getSelectedIndex());
			String mod = modToFileName(currFile);
			Files.setBook(mod);
			Book.getInstance().openBook();
		}
	}

	private String modToReadable(String currFile) {
		String modFileName = currFile.replace('_', ' ');
		if (modFileName.endsWith("/")) {
			modFileName = modFileName.substring(0, modFileName.length() - 1);
		}
		return modFileName;
	}

	private String modToFileName(String currFile) {
		return currFile.replace(' ', '_');
	}

	public List getListOfBooks() {
		Enumeration e;
		FileConnection currDir = null;
		browser = null;
		try {
			currDir = (FileConnection) Connector.open(LIBRARY_FOLDER);
			e = currDir.list();
			browser = new List("Books list", List.IMPLICIT);

			while (e.hasMoreElements()) {
				String fileName = (String) e.nextElement();
				if (isFolder(fileName)) {
					String mod = modToReadable(fileName);
					browser.append(mod, null);
				}
			}
			browser.setSelectCommand(view);
			browser.setCommandListener(this);
			if (currDir != null) {
				currDir.close();
			}
		} catch (IOException ioe) {
			Book.debugAlert("Error while browsing folders");
		}
		return browser;
	}

	private boolean isFolder(String fileName) throws IOException {
		boolean result = false;
		FileConnection c = (FileConnection) Connector.open(LIBRARY_FOLDER + "/"
				+ fileName);
		if (c != null) {
			result = c.isDirectory();
		}
		c.close();
		return result;
	}
}
